package com.example.sociamedia.interaction.controller;

import com.example.sociamedia.interaction.dto.PrivateMessageRequest;
import com.example.sociamedia.interaction.dto.PrivateMessageResponse;
import com.example.sociamedia.interaction.entity.PrivateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/messages")
public class PrivateMessageController {
    private final PrivateMessageService privateMessageService;

    @Autowired
    public PrivateMessageController(PrivateMessageService privateMessageService) {
        this.privateMessageService = privateMessageService;
    }

    @PostMapping("")
    public ResponseEntity<PrivateMessageResponse> sendMessage(@RequestHeader("Authorization") String sessionToken, @RequestBody PrivateMessageRequest request) {
        PrivateMessageResponse resp = privateMessageService.sendMessage(sessionToken, request);
        return new ResponseEntity<>(resp, resp.isSuccess() ? HttpStatus.OK : HttpStatus.BAD_REQUEST);
    }

    @GetMapping("/history/{otherUserId}")
    public ResponseEntity<List<PrivateMessage>> getMessagesWithUser(@RequestHeader("Authorization") String sessionToken, @PathVariable Long otherUserId) {
        return ResponseEntity.ok(privateMessageService.getMessagesWithUser(sessionToken, otherUserId));
    }

    @GetMapping("/conversations")
    public ResponseEntity<List<PrivateMessage>> getConversations(@RequestHeader("Authorization") String sessionToken) {
        return ResponseEntity.ok(privateMessageService.getConversations(sessionToken));
    }

    @GetMapping("/unread/count")
    public ResponseEntity<Integer> getUnreadCount(@RequestHeader("Authorization") String sessionToken) {
        int count = privateMessageService.countUnreadMessages(sessionToken);
        return ResponseEntity.ok(count);
    }

    @PostMapping("/read/{senderId}")
    public ResponseEntity<Integer> markMessagesAsRead(@RequestHeader("Authorization") String sessionToken, @PathVariable Long senderId) {
        int updated = privateMessageService.markMessagesAsRead(sessionToken, senderId);
        return ResponseEntity.ok(updated);
    }

    @GetMapping("/unread/list")
    public ResponseEntity<List<java.util.Map<String, Object>>> getUnreadList(@RequestHeader("Authorization") String sessionToken) {
        return ResponseEntity.ok(privateMessageService.getUnreadList(sessionToken));
    }
} 